package com.starsky.common.rabbitmq.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消息发送
 */
@Slf4j
@Component
public class RabbitMQService{

    @Autowired
    private ConnectionFactory connectionFactory;

    /**
     * 创建并绑定队列到指定交换机
     * @param exchangeName： 交换机
     * @param queueName： 队列名称
     * @param routingKey：路由key
     * @return success
     */
    public boolean createQueue(String exchangeName, String queueName, String routingKey) {
        boolean success = false;
        try {
            RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
            rabbitAdmin.declareQueue(new Queue(queueName));
            Binding binding = BindingBuilder.bind(new Queue(queueName))
                    .to(new DirectExchange(exchangeName, true, false))
                    .with(routingKey);
            rabbitAdmin.declareBinding(binding);
            success = true;
        } catch (Exception e) {
            e.getStackTrace();
            log.error(e.getMessage());
        } finally {
            return success;
        }
    }

}
